<template>
  <div id="home-page">
    <!-- 搜索框部分 -->
    <div class="search-container" :class="{ 'search-fixed': isSearchFixed }">
      <div class="search-wrapper">
        <a-row justify="center" align="middle">
          <a-col :xs="24" :sm="22" :md="20" :lg="18" :xl="16" :xxl="14">
            <div class="search-box">
              <a-input-search
                v-model:value="params.searchText"
                placeholder="输入关键词搜索"
                enter-button
                size="large"
                allow-clear
                @search="onSearch"
              >
                <template #addonBefore>
                  <a-select v-model:value="selectSearchType" class="search-type-select">
                    <a-select-option value="1">图片</a-select-option>
                    <a-select-option value="2">设计</a-select-option>
                    <a-select-option value="3">视频</a-select-option>
                    <a-select-option value="4">字体</a-select-option>
                  </a-select>
                </template>
              </a-input-search>

              <div class="search-actions">
                <a-tooltip>
                  <template #title>以图搜图</template>
                  <a-button
                    @click="openSearchModal = true"
                    :icon="h(CameraOutlined)"
                    class="action-btn camera-btn"
                  ></a-button>
                </a-tooltip>

                <a-tooltip>
                  <template #title>筛选条件</template>
                  <a-button
                    class="action-btn filter-btn"
                    :class="{ active: showFilter || hasActiveFilters }"
                    @click="toggleFilter"
                  >
                    <FilterOutlined />
                  </a-button>
                </a-tooltip>
              </div>
            </div>

            <!-- 筛选条件面板 -->
            <div class="filter-panel" v-show="showFilter">
              <!-- 分类标签页 -->
              <a-tabs v-model:activeKey="activeKey" @change="onSearch" class="category-tabs">
                <a-tab-pane key="all" tab="全部"></a-tab-pane>
                <a-tab-pane
                  v-for="category in tagCategoryOptions.categoryList"
                  :key="category"
                  :tab="category"
                >
                </a-tab-pane>
              </a-tabs>

              <!-- 标签选择 -->
              <div class="tag-container">
                <span class="tag-label">标签:</span>
                <a-space :size="[0, 8]" wrap>
                  <a-checkable-tag
                    v-for="(tag, index) in tagCategoryOptions.tagList"
                    :key="tag"
                    v-model:checked="selectTags[index]"
                    @change="onSearch"
                    class="custom-tag"
                  >
                    {{ tag }}
                  </a-checkable-tag>
                </a-space>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>

    <!-- 瀑布流图片展示 -->
    <div class="content-wrapper" ref="waterfallRef">
      <ImageWaterfall v-model="pictureList" />

      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
      </div>

      <div v-if="isNoMore" class="no-more-container">
        <span>没有更多内容了</span>
      </div>
    </div>

    <!-- 以图搜图弹窗 -->
    <PictureSearchByPicture v-model="openSearchModal" />

    <a-modal
      v-model:visible="showIntroModal"
      title="欢迎体验「触图万象」企业级智能协同图库"
      width="700px"
      :footer="null"
      centered
      class="intro-modal"
    >
      <a-row gutter="16">
        <a-col :span="12">
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="智能搜图" description="支持关键词、以图搜图、标签检索" />
            <div class="tech-tag">jsoup、百度搜图</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="AI助手" description="智能问答、图片理解、辅助创作" />
            <div class="tech-tag">通义千问(qwen)</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="AI扩图" description="智能图片补全、无损放大" />
            <div class="tech-tag">通义千问(qwen)</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="空间分析" description="用户/内容数据可视化" />
            <div class="tech-tag">ECharts</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta
              title="RBAC权限控制"
              description="支持公共空间、团队空间、私人空间多级权限管理"
            />
            <div class="tech-tag">RBAC模型</div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="实时聊天" description="在线沟通、协作" />
            <div class="tech-tag">WebSocket</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="点赞/评论" description="互动反馈、内容评价" />
            <div class="tech-tag">set、评论系统</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="好友关注" description="关注好友、内容动态" />
            <div class="tech-tag">set/zset</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="信息推送" description="实时通知、动态提醒" />
            <div class="tech-tag">zset</div>
          </a-card>
          <a-card bordered hoverable class="intro-card">
            <a-card-meta title="团队共享编辑" description="团队成员可实时协作编辑图片及信息" />
            <div class="tech-tag">WebSocket</div>
          </a-card>
        </a-col>
      </a-row>
      <a-divider />
      <div style="text-align: center; font-weight: bold; font-size: 16px; color: #1890ff">
        智能 · 协同 · 高效 · 可扩展 —— 让每一张图片都能被高效管理与智能利用！
      </div>
      <div style="margin-top: 16px; text-align: right">
        <a-checkbox v-model:checked="noMoreShow">下次不再提示</a-checkbox>
        <a-button type="primary" @click="closeIntroModal" style="margin-left: 16px"
          >我知道了</a-button
        >
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
// 请求参数
import { h, onMounted, reactive, ref, onUnmounted, computed } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageWithCacheUsingPost,
} from '@/api/pictureController.ts'
import { CameraOutlined, FilterOutlined } from '@ant-design/icons-vue'
import PictureSearchByPicture from '@/components/image/PictureSearchByPicture.vue'
import ImageWaterfall from '@/components/image/ImageWaterfall.vue'

const params = reactive<API.listPictureByPageUsingGETParams>({
  current: 1,
  pageSize: 12,
  sortField: 'create_time',
  sortOrder: 'descend',
})

const openSearchModal = ref(false)
const selectSearchType = ref('1')

//  total
const total = ref(0)

// 标签列表
const selectTags = reactive([])

// 分类
const activeKey = ref('')

// 定义标签option和分类option
const tagCategoryOptions = ref<API.PictureTagCategory>({
  categoryList: [],
  tagList: [],
})

const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code != 0) {
    return
  }
  tagCategoryOptions.value = res.data.data || { categoryList: [], tagList: [] }
}

// 获取数据
const isNextPage = ref(false)
const pictureList = ref<API.PictureVO[]>([])
const loading = ref(false)
const isNoMore = ref(false)

const getPictureList = async () => {
  loading.value = true
  try {
    const newParams = {
      ...params,
      tags: [] as string[],
    }
    // 判断类型
    if (activeKey.value !== 'all') {
      newParams.category = activeKey.value
    }
    // 选择标签
    selectTags.forEach((tag, index) => {
      if (tag && tagCategoryOptions.value.tagList?.[index]) {
        newParams.tags.push(tagCategoryOptions.value.tagList[index])
      }
    })

    console.log('请求参数:', newParams)
    const res = await listPictureVoByPageWithCacheUsingPost({ ...newParams })

    if (res.data.code !== 0) {
      console.error('获取数据失败:', res.data.message)
      return
    }

    if (isNextPage.value) {
      const newRecords = res.data.data?.records || []
      console.log('加载更多数据:', newRecords.length)
      if (newRecords.length === 0) {
        isNoMore.value = true
        console.log('没有更多数据了')
      } else {
        newRecords.forEach((item) => {
          pictureList.value.push(item)
        })
      }
    } else {
      pictureList.value = res.data.data?.records || []
      isNoMore.value = false
    }
    total.value = res.data.data?.total || 0
  } catch (error) {
    console.error('获取图片列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const onSearch = () => {
  params.current = 1
  isNoMore.value = false
  scrollLock = false
  pictureList.value = []
  getPictureList()
}

const nextPage = async () => {
  if (params.current !== undefined) {
    params.current += 1
    isNextPage.value = true
    await getPictureList()
    isNextPage.value = false
  }
}

// 搜索框固定状态
const isSearchFixed = ref(false)

// 节流锁，防止连续触发加载
let scrollLock = false

// 修改滚动监听逻辑，使用ref引用瀑布流容器
const waterfallRef = ref(null)

const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop
  const scrollHeight = document.documentElement.scrollHeight
  const clientHeight = document.documentElement.clientHeight

  // 更新搜索框固定状态
  isSearchFixed.value = scrollTop > 200

  // 提前 200px 触发加载
  const scrollTrigger = scrollHeight - clientHeight - 200

  if (
    scrollTop > scrollTrigger &&
    !loading.value &&
    !isNoMore.value &&
    !scrollLock &&
    pictureList.value.length > 0 // 确保有初始数据
  ) {
    console.log('触发加载更多:', {
      scrollTop,
      scrollHeight,
      clientHeight,
      scrollTrigger,
      currentPage: params.current,
      loading: loading.value,
      isNoMore: isNoMore.value,
      scrollLock,
    })
    scrollLock = true
    loadMore()
  }
}

const loadMore = async () => {
  if (loading.value || isNoMore.value) {
    scrollLock = false
    return
  }

  console.log('开始加载更多数据，当前页码:', params.current)

  try {
    loading.value = true
    await nextPage()
  } catch (error) {
    console.error('加载更多数据失败:', error)
  } finally {
    loading.value = false
    // 延迟释放锁，防止频繁触发
    setTimeout(() => {
      scrollLock = false
      console.log('释放滚动锁')
    }, 500)
  }
}

// 添加筛选面板显示状态
const showFilter = ref(false)

// 切换筛选面板显示状态
const toggleFilter = () => {
  showFilter.value = !showFilter.value
}

// 在 script 部分添加计算属性
const hasActiveFilters = computed(() => {
  // 检查是否有选中的标签
  const hasSelectedTags = selectTags.some((tag) => tag === true)
  // 检查是否选择了特定分类
  const hasSelectedCategory = activeKey.value !== '' && activeKey.value !== 'all'

  return hasSelectedTags || hasSelectedCategory
})

const showIntroModal = ref(false)
const noMoreShow = ref(false)

const closeIntroModal = () => {
  showIntroModal.value = false
  if (noMoreShow.value) {
    localStorage.setItem('noMoreIntro', '1')
  }
}

onMounted(() => {
  console.log('组件挂载，初始化数据')
  window.addEventListener('scroll', handleScroll)
  getPictureList()
  getTagCategoryOptions()
  if (!localStorage.getItem('noMoreIntro')) {
    showIntroModal.value = true
  }
})

onUnmounted(() => {
  console.log('组件卸载，移除滚动监听')
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped lang="scss">
#home-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%);
  padding-bottom: 40px;
  padding-top: 64px; // 为顶部导航栏预留空间
}

/* 内容包装器 - 统一宽度控制 */
.content-wrapper {
  width: 100%;
  max-width: 100%;
  padding: 0 16px;
  margin: 32px auto;
  box-sizing: border-box;

  @media (min-width: 576px) {
    padding: 0 24px;
  }

  @media (min-width: 992px) {
    padding: 0 32px;
    width: 92%;
  }

  @media (min-width: 1200px) {
    width: 88%;
  }

  @media (min-width: 1600px) {
    width: 80%;
    max-width: 1800px;
  }
}

/* 搜索框容器样式 */
.search-container {
  position: relative;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  padding: 24px 0;
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  margin: 32px auto;
  width: 100%;
  max-width: 100%;
  padding-left: 16px;
  padding-right: 16px;
  box-sizing: border-box;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  @media (min-width: 576px) {
    padding-left: 24px;
    padding-right: 24px;
    width: 92%;
  }

  @media (min-width: 992px) {
    padding-left: 32px;
    padding-right: 32px;
    width: 92%;
  }

  @media (min-width: 1200px) {
    width: 88%;
  }

  @media (min-width: 1600px) {
    width: 80%;
    max-width: 1800px;
  }

  &.search-fixed {
    position: fixed;
    top: 64px; // 调整固定位置，避免遮挡导航栏
    left: 0;
    right: 0;
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding-top: 16px;
    padding-bottom: 16px;
    background: rgba(255, 255, 255, 0.98);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    animation: slideDown 0.3s ease;
    border-radius: 0 0 24px 24px;

    .search-wrapper {
      width: 100%;
      max-width: 100%;
      padding-left: 16px;
      padding-right: 16px;

      @media (min-width: 576px) {
        padding-left: 24px;
        padding-right: 24px;
        width: 92%;
        margin: 0 auto;
      }

      @media (min-width: 992px) {
        padding-left: 32px;
        padding-right: 32px;
        width: 92%;
      }

      @media (min-width: 1200px) {
        width: 88%;
      }

      @media (min-width: 1600px) {
        width: 80%;
        max-width: 1800px;
      }
    }
  }

  .search-wrapper {
    width: 100%;
  }

  .search-box {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;

    @media (max-width: 576px) {
      .ant-input-search {
        flex: 1 1 100%;
        margin-bottom: 12px;
      }

      .search-actions {
        width: 100%;
        justify-content: center;
      }
    }

    @media (min-width: 577px) {
      flex-wrap: nowrap;

      .ant-input-search {
        flex: 1;
      }
    }
  }

  .search-actions {
    display: flex;
    gap: 8px;
  }

  .action-btn {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: #f0f5ff;
    border: none;
    color: #1890ff;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e6f7ff;
      transform: translateY(-2px);
    }

    &.active {
      background: #1890ff;
      color: #fff;
    }
  }

  .filter-panel {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid rgba(0, 0, 0, 0.06);
    animation: slideDown 0.3s ease;
  }

  .category-tabs {
    margin-bottom: 20px;

    :deep(.ant-tabs-nav) {
      margin-bottom: 0;

      &::before {
        border-bottom: none;
      }

      .ant-tabs-tab {
        padding: 8px 16px;
        font-size: 14px;
        transition: all 0.3s ease;

        &:hover {
          color: #1890ff;
        }

        &.ant-tabs-tab-active {
          .ant-tabs-tab-btn {
            color: #1890ff;
            font-weight: 500;
          }
        }
      }

      .ant-tabs-ink-bar {
        background: #1890ff;
        height: 3px;
        border-radius: 3px;
      }
    }
  }

  .tag-container {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    flex-wrap: wrap;

    .tag-label {
      color: #666;
      font-weight: 500;
      font-size: 14px;
      margin-right: 8px;
    }

    .custom-tag {
      border-radius: 12px;
      font-size: 13px;
      padding: 4px 12px;
      background: #f0f5ff;
      color: #1890ff;
      border: none;
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        background: #e6f7ff;
        transform: translateY(-2px);
      }

      &.ant-tag-checkable-checked {
        background: #1890ff;
        color: #fff;
      }
    }
  }
}

/* 轮播图样式 */
.carousel {
  width: 100%;
  height: 0;
  padding-bottom: 42%; // 比例控制
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  position: relative;

  @media (max-width: 768px) {
    padding-bottom: 56%; // 移动端更高一些
  }

  .carousel-item {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .carousel-content {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px;
      background: rgba(0, 0, 0, 0.3);
    }

    .carousel-logo {
      font-size: 2.5rem;
      font-family: '楷体';
      font-weight: bold;
      margin-bottom: 1.5rem;
      color: #fff;
      text-align: center;
    }

    .carousel-title {
      font-size: 1.5rem;
      text-align: center;
      margin-bottom: 1.5rem;
      color: #fff;
      font-weight: 500;
    }

    .carousel-text {
      font-size: 2rem;
      font-weight: bold;
      font-family: '宋体';
      margin: 0;
      color: #fff;
      text-align: center;
    }
  }
}

/* 瀑布流容器 */
.loading-container {
  text-align: center;
  padding: 40px 0;
}

.no-more-container {
  text-align: center;
  padding: 40px 0;
  color: #666;
  font-size: 16px;
  letter-spacing: 2px;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 576px) {
  .search-container {
    margin: 16px auto;
    padding-top: 16px;
    padding-bottom: 16px;
    border-radius: 16px;
  }

  .content-wrapper {
    margin: 16px auto;
  }

  .carousel {
    border-radius: 16px;
  }
}

.intro-modal {
  .ant-modal-content {
    border-radius: 16px;
    background: linear-gradient(135deg, #fafdff 0%, #e4e9f2 100%);
  }
}
.intro-card {
  margin-bottom: 12px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.08);
}
.tech-tag {
  margin-top: 8px;
  color: #888;
  font-size: 13px;
}
</style>
